//
//  MessageManager.m
//  HotWord
//
//  Created by Rainbow on 7/26/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MessageManager.h"
#import "ITTObjectSingleton.h"
#import "UserManager.h"
#import "ServiceHelper.h"

#define ALL_MESSAGES    @"ALL_MESSAGES"
#define MESSAGE_USER_IDS    @"MESSAGE_USER_IDS"
#define UPDATE_TIMER_DURATION   30
#define LAST_UPDATE_TIME    @"LAST_UPDATE_TIME"

@implementation MessageManager
@synthesize messages;
@synthesize messageUserIds;
@synthesize lastGetMessageTime;
@synthesize newMessageCount;

ITTOBJECT_SINGLETON_BOILERPLATE(MessageManager, sharedManager)
- (id)init{
    self = [super init];
	if (self) {
		[self restore];
	}
	return self;
}


- (void)addMessage:(Message *)message withUserId:(NSString *)userId
{
    message.isReaded = [NSNumber numberWithBool:YES];
    if (!_isFirstGetMessage) {
        if (![message.senderUserId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
            message.isReaded = [NSNumber numberWithBool:NO];
            self.newMessageCount ++;
        }
    }
    NSMutableArray *userMessages = [self.messages objectForKey:userId];
    if (!userMessages) {
        userMessages = [NSMutableArray array];
    }
    [userMessages addObject:message];
    [self.messages setObject:userMessages forKey:userId];
    
    [self.messageUserIds removeObject:userId];
    [self.messageUserIds insertObject:userId atIndex:0];
}


- (void)addMessages:(NSMutableArray *)newMessages
{
    for (Message *message in newMessages) {
        NSString *userId;
        NSString *currentUserId = [UserManager sharedManager].currentUser.userId;
        if ([currentUserId isEqualToString:message.recevierUserId]) {
            userId = message.senderUserId;
        }
        else {
            userId = message.recevierUserId;
        }
        [self addMessage:message withUserId:userId];
    }
    
    NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:self.messages];
    [USER_DEFAULT setObject:messageData forKey:ALL_MESSAGES];
    [USER_DEFAULT setObject:self.messageUserIds forKey:MESSAGE_USER_IDS];
    [USER_DEFAULT synchronize];
    
}


- (void)removeMessageByUserId:(NSString *)userId
{
    [self.messages removeObjectForKey:userId];
    id needRemoveId;
    for (NSString *existId in self.messageUserIds) {
        if ([userId isEqualToString:userId]) {
            needRemoveId = userId;
            break;
        }
    }
    [self.messageUserIds removeObject:needRemoveId];
    NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:self.messages];
    [USER_DEFAULT setObject:messageData forKey:ALL_MESSAGES];
    [USER_DEFAULT setObject:self.messageUserIds forKey:MESSAGE_USER_IDS];
    [USER_DEFAULT synchronize];
}

- (NSMutableArray *)getMessagesByUserId:(NSString *)userId
{
    NSMutableArray *userMessages = [self.messages objectForKey:userId];
    for (Message *message in userMessages) {
        if (![message.isReaded boolValue]) {
            message.isReaded = [NSNumber numberWithBool:YES];
            if (self.newMessageCount > 0) {
                self.newMessageCount--;
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_RECEIVE_MESSAGE object:nil];
        }
    }
    
    NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:self.messages];
    [USER_DEFAULT setObject:messageData forKey:ALL_MESSAGES];
    [USER_DEFAULT synchronize];
    return userMessages;
}

- (NSMutableArray *)getLastestMessages
{
    NSMutableArray *lastestMessages = [NSMutableArray array];
    for (NSString *userId in self.messageUserIds) {
        NSArray *userMessages = [self.messages objectForKey:userId];
        [lastestMessages addObject:[userMessages lastObject]];
    }
    return lastestMessages;
}

- (void)receiveMessage
{
    if (![UserManager sharedManager].currentUser.userId) {
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    if (self.lastGetMessageTime == 0) {
        _isFirstGetMessage = YES;
        [params setObject:@"0" forKey:@"notme"];
    }
    else {
        
        [params setObject:@"1" forKey:@"notme"];
    }
    if (!self.lastGetMessageTime) {
        self.lastGetMessageTime = @"0";
    }
    [params setObject:self.lastGetMessageTime forKey:@"timestamp"];
    NSLog(@"Message timestamp: %@", self.lastGetMessageTime);
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeReceiveMsg WithParameters:params AndCallBackScope:self AndSuccessSel:@"receiveMessageSuccess:" AndFailedSel:@"receiveMessageFailed:"];
}

- (void)receiveMessageSuccess:(NSObject *)result
{
    NSMutableArray *newMessages = [NSMutableArray array];
    NSDictionary *dataDic = [(NSDictionary *)result objectForKey:@"data"];
    if (![dataDic isKindOfClass:[NSDictionary class]]) {
        if ([@"0" isEqualToString:self.lastGetMessageTime]) {
            [USER_DEFAULT setObject:self.lastGetMessageTime forKey:LAST_UPDATE_TIME];
        }
        return;
    }
    
    
    for (NSString *key in [dataDic allKeys]) {
        NSDictionary *userDialogDic = [dataDic objectForKey:key];
        NSDictionary *userInfo = [userDialogDic objectForKey:@"info"];
        
        NSArray *dialogs = [userDialogDic objectForKey:@"dialog"];
        
        if ([dialogs count] > 0) {
            AudioServicesPlaySystemSound ( kSystemSoundID_Vibrate);
        }
        for (NSDictionary *dialogsDic in dialogs) {
            for (NSString *dialogKey in [dialogsDic allKeys]) {
                if ([dialogKey doubleValue] > [self.lastGetMessageTime doubleValue]) {
                    self.lastGetMessageTime = [NSString stringWithFormat:@"%f", [dialogKey doubleValue] + 1];
                    
                }
                NSDictionary *dialogDic = [dialogsDic objectForKey:dialogKey];
                Message *message = [[[Message alloc] init] autorelease];
                message.dialogEmail = [UtilHelper getStringValue:[userInfo objectForKey:@"email"]];
                message.dialogNickname = [UtilHelper getStringValue:[userInfo objectForKey:@"nick"]];
                message.dialogAvator = [UtilHelper getStringValue:[userInfo objectForKey:@"avater"]];
                message.content = [UtilHelper getStringValue:[dialogDic objectForKey:@"content"]];
                message.timestamp = dialogKey;
                message.senderUserId = [UtilHelper getStringValue:[dialogDic objectForKey:@"sender"]];
                if ([key isEqualToString:message.senderUserId]) {
                    message.recevierUserId = [UserManager sharedManager].currentUser.userId;
                }
                else {
                    message.recevierUserId = key;
                }
                [newMessages insertObject:message atIndex:0];
            }
        }
    }
    [self addMessages:newMessages];
    [USER_DEFAULT setObject:self.lastGetMessageTime forKey:LAST_UPDATE_TIME];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_RECEIVE_MESSAGE object:nil];
    _isFirstGetMessage = NO;
}

- (void)receiveMessageFailed:(NSObject *)result
{
    if ([@"0" isEqualToString:self.lastGetMessageTime]) {
        [USER_DEFAULT setObject:self.lastGetMessageTime forKey:LAST_UPDATE_TIME];
    }
}

- (void)restore{
    
    NSData *messageData = [USER_DEFAULT objectForKey:ALL_MESSAGES];
    if (messageData) {
        self.messages = [NSKeyedUnarchiver unarchiveObjectWithData:messageData];
    }
    if (!self.messages) {
        self.messages = [NSMutableDictionary dictionary];
    }
    self.messageUserIds = [USER_DEFAULT objectForKey:MESSAGE_USER_IDS];
    if (!self.messageUserIds) {
        self.messageUserIds = [NSMutableArray array];
    }
}

- (void)sendReceiveMessage
{
    
    self.lastGetMessageTime = [USER_DEFAULT objectForKey:LAST_UPDATE_TIME];
    [self receiveMessage];
    _messageUpdateTimer = [[NSTimer scheduledTimerWithTimeInterval:UPDATE_TIMER_DURATION target:self selector:@selector(receiveMessage) userInfo:nil repeats:YES] retain];
}

- (void)clearMessages
{
    _isFirstGetMessage = YES;
    [_messageUpdateTimer invalidate];
    _messageUpdateTimer = nil;
    self.lastGetMessageTime = 0;
    [self.messages removeAllObjects];
    [self.messageUserIds removeAllObjects];
    self.newMessageCount = 0;
    [USER_DEFAULT removeObjectForKey:ALL_MESSAGES];
    [USER_DEFAULT removeObjectForKey:MESSAGE_USER_IDS];
    [USER_DEFAULT removeObjectForKey:LAST_UPDATE_TIME];
}

- (void)dealloc{
    
    [_messageUpdateTimer invalidate];
    _messageUpdateTimer = nil;
    [lastGetMessageTime release];
    [messageUserIds release];
    [messages release];
	[super dealloc];
}
@end
